import Layouts from '@/layouts/index.vue'
import router from '@/router/index'
import { defineStore } from 'pinia'

const modules = import.meta.glob('@/views/**/index.vue')

const cacheListStr = sessionStorage.getItem('menuList')
const cacheList = cacheListStr ? JSON.parse(cacheListStr) : []

function getMenuComponent(menu: any) {
  // 路径格式 item.path为 /system/menu 转为SystemMenu
  // 1. 移除开头的斜杠
  const parts = menu.path.replace(/^\//, '').split('/')
  const componentName = parts.map((part: string) => part.charAt(0).toUpperCase() + part.slice(1)).join('')
  let componentPath = ''
  for (const key in modules) {
    if (key.includes(menu.component)) {
      componentPath = key
      break
    }
  }
  return {
    path: menu.path,
    name: componentName,
    meta: { title: menu.menuName },
    component: () => modules[componentPath](),
  }
}

const useMenuTreeStore = defineStore('menu-tree', {
  state: () => ({
    menuList: cacheList,
    routerDone: false,
  }),
  actions: {
    setMenuList(list: any[]) {
      sessionStorage.setItem('menuList', JSON.stringify(list))
      this.menuList = list
      return this.generateRoutes()
    },
    // 生成路由
    generateRoutes() {
      this.menuList.forEach((item: any) => {
        const children = item.isFrame === 1 ? [] : item.children.map((child: any) => getMenuComponent(child))
        const routeName = item.path.replace('/', '')
        router.hasRoute(routeName) && router.removeRoute(routeName)
        router.addRoute({
          path: item.path,
          name: routeName,
          meta: { title: item.menuName },
          component: Layouts,
          children,
        })
      })
      this.routerDone = true
      return Promise.resolve(this.menuList)
    },
    // 获取菜单列表
    getMenuList() {
      return this.menuList
    },
  },
})

export default useMenuTreeStore
